<?php

namespace App\Models;

use App\Services\Api\WorkService;
use Illuminate\Database\Eloquent\Model;
use SebastianBergmann\Comparator\Book;
use Illuminate\Support\Facades\Cache;
use App\Admin\Controllers\AdminApiController;

class PersonalRead extends Model
{
    //塾生学习
    protected $table='personal_read';

    public function book(){
        //return $this->belongsTo(BookModel::class,'book_id','id');
        return $this->belongsToMany(BookModel::class, 'personal_read_book',
            'personal_read_id', 'book_id');

    }

    public function getCoveUrlAttribute($value){
        return oss_domain().'/'.$value;
    }

    //作业
    public function personal_class_work(){
        return $this->hasMany(ClassWorkModel::class, 'personal_read_id','id');
    }

    public function many_book(){
        return $this->hasMany(PersonalReadBook::class,'personal_read_id','id');
    }

    public function article(){
        //return $this->hasMany(ArticleModel::class,'book_id','book_id');
    }

    public function class_team(){
        return $this->belongsTo(ActivityTeamUser::class,'id','key_id');
    }

    public function class_work(){
        return $this->hasMany(ClassWorkModel::class,'personal_read_id','id');
    }

    public function personal_read_register(){
        return $this->hasOne(PersonalReadRegister::class,'personal_read_id','id');
    }



    public function personal_read_list($user_id){
        //不优化了 需求不明确 修改要与前端沟通
        //报过名的先排
        $data = $this
            ->with([
                'class_team'=>function($q)use($user_id){
                    $q->where('user_id',$user_id)->select(['team_id','key_id','team_user_stash','created_at'])
                        ->where('team_type',3);
                },
                //'personal_read_register'
            ])
            ->orderBy('id','desc')
            ->paginate(3)
            ->toArray();
        foreach ($data['data'] as $k=>$v){
            if(!empty($v['class_team'])){
                $data['data'][$k]['order'] = 1;
                //获取缓存
                $redis_key = env('REDIS_KEY_TEAM_WORK').$v['class_team']['team_id'];
                $work_data = Cache::get($redis_key);
                if(!empty($work_data)){
                    $work_data = json_decode($work_data,true);
                }else{
                    $api = new AdminApiController();
                    $res = $api->redis_team_book_article($v['class_team']['key_id'],3,$v['class_team']['team_id']);
                    $work_data = Cache::get($redis_key);
                    $work_data = json_decode($work_data,true);
                }
                $today = date("Y-m-d");
                if(!empty($work_data[$today])){
                    $data['data'][$k]['class_team']['read_book'] = $work_data[$today];
                }else{
                    $data['data'][$k]['class_team']['read_book'] = [];
                }
            }else{
                $data['data'][$k]['order'] = 0;
            }
        }
        $data['data'] = arraySort($data['data'], 'order');
        return $data;
    }

    public function personal_read_info($personal_read_id,$user_id){
/*       $teamObj = ActivityTeamUser::where('user_id',$user_id)
            ->where('key_id',$personal_read_id)
            ->where('team_type',3)
            ->with(['team'])
            ->first();

        if(empty($teamObj)){
            return [];
        }

        if(!empty($teamObj->wee_holiday)){
            $w = date("w");
            //$wee_holiday = explode(',',$teamObj->wee_holiday);
            $wee_holiday = $teamObj->wee_holiday;

            if(in_array($w,$wee_holiday) && $w!=0){

                return [];
            }elseif ($w==0 && in_array('7',$wee_holiday)){

                return [];
            }

            $sta = strtotime($teamObj->day_holiday_start);
            $end = strtotime($teamObj->day_holiday_end);
            if($sta >0 && $end>0){
                //dd($teamObj->id,$sta,$end);
                $now_time = time();
                if($now_time>=$sta && $now_time<=$end){
                    return [];
                }
            }

        }
        //dd($teamObj);
        $days = app(WorkService::class)->get_total_work_date($teamObj->team->start_time,$teamObj->team->wee_holiday,$teamObj->team->day_holiday_start,$teamObj->team->day_holiday_end);
        //dd($days);
        if($days <= 0){
            return [];
        }
        $book = PersonalReadBook::where('personal_read_id',$personal_read_id)
            ->with([
                'article'
            ])
            ->orderBy('sort','asc')
            ->get()
            ->toArray();
        $article_number = 0;
        foreach ($book as $k=>$v){
            $article_number += count($v['article']);
            //排到那一本书

            if($article_number >= $days){
                $book_id = $v['book_id'];
                //計算该本书 排到第几章 不是第一本
                if($v['sort'] != 1){
                    $days = $days - count($v['article']);
                }
                break;
            }
        }
        //dd($days);
        if(empty($book_id)){
            return [];
        }
        $data = $this->where('id',$personal_read_id)
                ->with([
                'book'=>function($q)use($book_id){
                    $q->where('book.id',$book_id)->select([
                        'book.id',
                        'book.book_title',
                        'book.book_logo',
                        'book.author',
                        'book.article_number',
                        'book.synopsis',
                        'book.created_at',
                        ]);
                }
            ])
            ->first();
        $data->article = ArticleModel::where('book_id',$book_id)
            ->select([
                'id',
                'book_id',
                'article_title',
                'article_cover',
                'reader_link',
                'article_leader',
            ])
            ->orderBy('order','asc')
            ->take($days)
            ->get();
        return $data;*/
    }

    public function personal_read_array(){
        $data =  $this
            ->select([
                'id',
                'book_id as name',
            ])
            ->orderBy('created_at','desc')
            ->paginate(15)
            ->toArray();

        if(count($data['data'])>0){
            $bok_ids = array_column($data['data'], 'name');

            $data2 = BookModel::whereIn('id',$bok_ids)->pluck('book_title','id')->toArray();

            foreach ($data['data'] as $k=>$v){

                if(!empty($data2[$v['name']])){

                    $data['data'][$k]['name'] = $data2[$v['name']];
                }

            }
        }

        return $data;
    }

}
